package com.company.project.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
//import com.company.project.common.utils.BaiduPush;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.project.common.utils.BaiduPush;
import com.company.project.common.utils.RestUtil;
import com.company.project.common.websocket.WebSocket;
import com.company.project.pojo.Rest;
import com.company.project.pojo.FilePojo;
import com.company.project.pojo.ServiceCode;
import com.company.project.common.utils.JwtUtil;
import com.company.project.pojo.configFile.ConfigFile;
import com.company.project.pojo.contradiction.Contradiction;
import com.company.project.pojo.contradictionRecord.ContradictionRecord;
import com.company.project.pojo.contradictionRecord.ContradictionRecordDTO;
import com.company.project.pojo.contradictionRecord.ContradictionRecordForm;
import com.company.project.pojo.contradictionRecord.ContradictionRecordInfoVO;
import com.company.project.pojo.institution.Institution;
import com.company.project.pojo.user.User;
import com.company.project.service.*;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 矛盾推送记录 前端控制器
 * </p>
 *
 * @author 任建波
 * @since 2019-08-13
 */
@Api(value = "矛盾资料推送记录",tags = "矛盾资料推送记录")
@Controller
@RequestMapping("contradictionRecord")
public class ContradictionRecordController {

//    @Value("${file-url-prefix}")
    private String fileUrlPrefix;

    @Autowired
    IConfigFileService iConfigFileService;
    @Autowired
    private IContradictionRecordService iContradictionRecordService;
    @Autowired
    private IContradictionService iContradictionService;
    @Autowired
    private IUserService iUserService;
    @Autowired
    private IInstitutionService iInstitutionService;
    @Autowired
    HttpServletRequest request;

    @ApiOperation(value = "查询推送记录")
    @ApiImplicitParam(paramType="header", name = "token", value = "token", required = true, dataType = "String")
    @RequestMapping(value = "getContradictionRecordPage", method = RequestMethod.GET)
    @ResponseBody
    public Rest getContradictionRecordPage(Integer currentPage){
        IPage<ContradictionRecordDTO> pageInfo = iContradictionRecordService.getContradictionRecordList(currentPage);

        return RestUtil.rest(ServiceCode.CODE_200, "成功" , pageInfo);
    }

    @ApiOperation(value = "查询pc未读推送记录数")
    @ApiImplicitParam(paramType="header", name = "token", value = "token", required = true, dataType = "String")
    @RequestMapping(value = "getPCNotReadContradictionRecordCount", method = RequestMethod.GET)
    @ResponseBody
    public Rest getPCNotReadContradictionRecordCount(){
        Integer count = iContradictionRecordService.getPCNotReadContradictionRecordCount();

        return RestUtil.rest(ServiceCode.CODE_200, "成功" , count);
    }

    @ApiOperation(value = "设置pc推送记录为已读")
    @ApiImplicitParam(paramType="header", name = "token", value = "token", required = true, dataType = "String")
    @RequestMapping(value = "setcontradictionRecordPCRead", method = RequestMethod.POST)
    @ResponseBody
    public Rest setcontradictionRecordPCRead(Integer contradictionId, Integer institutionId){
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("contradiction_id", contradictionId);
        updateWrapper.eq("institution_id", institutionId);

        ContradictionRecord contradictionRecord = new ContradictionRecord();
        contradictionRecord.setIsPcRead(1);

        iContradictionRecordService.update(contradictionRecord, updateWrapper);

        return RestUtil.rest(ServiceCode.CODE_200, "成功");
    }

    @ApiOperation(value = "根据ContradictionId获取矛盾资料记录列表")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType="header", name = "token", value = "token", required = true, dataType = "String"),
        @ApiImplicitParam(paramType="query", value = "矛盾资料id", name = "contradictionId", required = true),
    })
    @RequestMapping(value = "getcontradictionRecordListByContradictionId", method = RequestMethod.GET)
    @ResponseBody
    public Rest getcontradictionRecordListByContradictionId(Integer contradictionId){
        List<ContradictionRecordDTO> contradictionRecordList = iContradictionRecordService.getcontradictionRecordListByContradictionId(contradictionId);

        return RestUtil.rest(ServiceCode.CODE_200, "成功" , contradictionRecordList);
    }

    @ApiOperation(value = "根据id获取矛盾资料记录")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType="header", name = "token", value = "token", required = true, dataType = "String"),
        @ApiImplicitParam(paramType="query", value = "矛盾资料id", name = "contradictionId", required = true, dataType = "int"),
        @ApiImplicitParam(paramType="query", value = "单位id", name = "institutionId", required = true, dataType = "int")
    })
    @RequestMapping(value = "getContradictionRecordById", method = RequestMethod.GET)
    @ResponseBody
    public Rest<ContradictionRecordInfoVO> getContradictionRecordById(Integer contradictionId, Integer institutionId){
        ConfigFile configFile = iConfigFileService.getById(1);
        fileUrlPrefix = configFile.getFileUrlPrefix();

        QueryWrapper<ContradictionRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("contradiction_id", contradictionId);
        queryWrapper.eq("institution_id", institutionId);

        ContradictionRecord contradictionRecord = iContradictionRecordService.getOne(queryWrapper);

        ContradictionRecordInfoVO contradictionRecordInfoVO = new ContradictionRecordInfoVO();
        if(contradictionRecord != null){
            BeanUtils.copyProperties(contradictionRecord, contradictionRecordInfoVO);
            contradictionRecordInfoVO.setImg(toFile(contradictionRecord.getImgUrl()));
            contradictionRecordInfoVO.setVideo(toFile(contradictionRecord.getVideoUrl()));
            contradictionRecordInfoVO.setAudio(toFile(contradictionRecord.getAudioUrl()));
            contradictionRecordInfoVO.setFile(toFile(contradictionRecord.getFileUrl()));
        }

        return RestUtil.rest(ServiceCode.CODE_200, "成功" , contradictionRecordInfoVO);
    }

    private FilePojo[] toFile(String str){
        if(str != null && !str.equals("")){
            String[] strs = str.split("@@");
            FilePojo[] filePojos = new FilePojo[strs.length];

            for (int i=0; i<strs.length ; i++){
                FilePojo filePojo = new FilePojo();
                filePojo.setUrl(fileUrlPrefix + strs[i]);
                filePojo.setName(strs[i].split("@_@")[1]);

                filePojos[i] = filePojo;
            }

            return filePojos;
        }else {
            return null;
        }
    }

    @ApiOperation(value = "推送矛盾资料")
    @ApiImplicitParam(paramType="header", name = "token", value = "token", required = true, dataType = "String")
    @RequestMapping(value = "pushContradiction", method = RequestMethod.POST)
    @ResponseBody
    public Rest pushContradiction(@RequestParam("contradictionId") Integer contradictionId, @RequestParam("institutionIds[]") Integer[] institutionIds){
        Claims claims = JwtUtil.parseJWT(request.getHeader("token"));
        Integer user_id = claims.get("user_id", Integer.class);

        QueryWrapper<ContradictionRecord> contradictionRecordQueryWrapper = new QueryWrapper<>();
        contradictionRecordQueryWrapper.eq("is_delete", 0);
        contradictionRecordQueryWrapper.eq("contradiction_id", contradictionId);
        contradictionRecordQueryWrapper.orderByDesc("input_time");
        List<ContradictionRecord> contradictionRecordList = iContradictionRecordService.list(contradictionRecordQueryWrapper);

        if(contradictionRecordList.size() > 0){
            ContradictionRecord contradictionRecordLast = contradictionRecordList.get(contradictionRecordList.size() - 1);

            Institution institution = iInstitutionService.getById(contradictionRecordLast.getInstitutionId());
            if(contradictionRecordLast != null && contradictionRecordLast.getStatus().equals(0)){
                return RestUtil.rest(ServiceCode.CODE_403, "【" + institution.getName() + "】待处理问题，不能推送");
            }
            if(contradictionRecordLast != null && contradictionRecordLast.getStatus().equals(1)){
                return RestUtil.rest(ServiceCode.CODE_403, "【" + institution.getName() + "】已解决问题，不能推送");
            }
        }

        for (Integer institutionId: institutionIds) {
            ContradictionRecord contradictionRecord = new ContradictionRecord();
            contradictionRecord.setContradictionId(contradictionId);
            contradictionRecord.setInputUserId(user_id);
            contradictionRecord.setInstitutionId(institutionId);
            contradictionRecord.setStatus(0);
            iContradictionRecordService.save(contradictionRecord);

            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("institution_id", institutionId);
            queryWrapper.eq("is_delete", 0);
            queryWrapper.isNotNull("push_id");
            List<User> userList = iUserService.list(queryWrapper);

            List<String> pushIdList = userList.stream().map(user->{
                        return user.getPushId();
                    }).collect(Collectors.toList());

            Contradiction contradiction = iContradictionService.getById(contradictionId);

            //百度推送
            BaiduPush.PushMessageByPushIds(contradiction.getTitle(), contradiction.getDescription(), pushIdList);
        }

        return RestUtil.rest(ServiceCode.CODE_200, "成功");
    }

    @ApiOperation(value = "处理矛盾资料")
    @ApiImplicitParam(paramType="header", name = "token", value = "token", required = true, dataType = "String")
    @RequestMapping(value = "handleContradiction", method = RequestMethod.POST)
    @ResponseBody
    public Rest handleContradiction(@RequestBody ContradictionRecordForm contradictionRecordForm) throws IOException {
        Contradiction contradiction = iContradictionService.getById(contradictionRecordForm.getContradictionId());
        if(contradiction.getStatus().equals(2)){
            return RestUtil.rest(ServiceCode.CODE_403, "该问题已解决，不用再处理");
        }

        Claims claims = JwtUtil.parseJWT(request.getHeader("token"));
        Integer institution_id = claims.get("institution_id", Integer.class);
        Integer user_id = claims.get("user_id", Integer.class);

        ContradictionRecord contradictionRecord = new ContradictionRecord();
        BeanUtils.copyProperties(contradictionRecordForm, contradictionRecord);
        contradictionRecord.setImgUrl(fileToSting(contradictionRecordForm.getImg()));
        contradictionRecord.setVideoUrl(fileToSting(contradictionRecordForm.getVideo()));
        contradictionRecord.setAudioUrl(fileToSting(contradictionRecordForm.getAudio()));
        contradictionRecord.setFileUrl(fileToSting(contradictionRecordForm.getFile()));
        contradictionRecord.setHandleTime(new Date());
        // 9999:两委      9998:书记     9997: 乡贤
        if(contradictionRecordForm.getHandleUserId() != null){
            contradictionRecord.setHandleUserId(contradictionRecordForm.getHandleUserId());
        } else {
            contradictionRecord.setHandleUserId(user_id);
        }

        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("contradiction_id", contradictionRecordForm.getContradictionId());
        updateWrapper.eq("institution_id", institution_id);

        iContradictionRecordService.update(contradictionRecord, updateWrapper);

        //设置问题解决人
        if(contradictionRecordForm.getStatus().equals(1)){
            if(contradictionRecordForm.getHandleUserId() != null){
                contradiction.setSolveUserId(contradictionRecordForm.getHandleUserId());
            } else {
                contradiction.setSolveUserId(user_id);
            }
            contradiction.setSolveTime(new Date());
            iContradictionService.updateById(contradiction);
        }

        WebSocket.sendInfo("handleContradiction");

        return RestUtil.rest(ServiceCode.CODE_200, "成功");
    }

    private String fileToSting(FilePojo[] filePojos){
        if(filePojos != null && filePojos.length > 0){
            String str = "";
            for (int i=0; i<filePojos.length ; i++){
                if(i < filePojos.length - 1){
                    str += filePojos[i].getUrl() + "@@";
                }else if(i == filePojos.length - 1){
                    str += filePojos[i].getUrl();
                }
            }
            return str;
        }else {
            return null;
        }
    }

}

